// 层序遍历

function levelOrder(root) {
    if (!root) return [];

    let res = [], queue = [root];
    while (queue.length) {
        let n = queue.length;
        let temp = [];
        
        for (let i = 0; i < n; i++) {
            let node = queue.shift();
            temp.push(node.val);

            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        };
        res.push(temp);
    };
    return res;
};





// test
const root = {
    val: 3,
    left: {
        val: 9,
    },
    right: {
        val: 20,
        left: {
            val: 15,
        }, 
        right: {
            val: 7,
        }
    },
};

const res = levelOrder(root);
console.log(res);